package com.lifeservice.util;

import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description: 获取当年法定节假日以及周末
 * @Author: yuan_fengzhuan
 * @Date: 2023/3/30
 * @Version: V1.0
 */
@Component
public class HolidayCrawler {

    /**
     * 年度法定节假日、公休日查询接口地址
     */
    private static final String YEAR_HOLIDAY_URL = "https://api.apihubs.cn/holiday/get?field=date,weekend&year=2023&workday=2&order_by=1&cn=1&page=1&size=500";
    /**
     * http请求工具类
     */
    private static final RestTemplate REST_TEMPLATE = new RestTemplate();


    public  List<String> initHolidays() throws ParseException {
        long ts = System.currentTimeMillis();
        List<String> holidays = new ArrayList<>();
        Map<String, Object> result = REST_TEMPLATE.getForObject(String.format(YEAR_HOLIDAY_URL, ts, ts), Map.class);
        if (null != result) {
            String code = String.valueOf(result.get("code"));
            if (code.equals("0")) {
                Map data = (Map) result.get("data");
                if (null != data) {
                    List<Map<String, Object>> list = (List<Map<String, Object>>) data.get("list");
                    int i = 0;
                    String date = null;
                    SimpleDateFormat sdfD = new SimpleDateFormat("yyyyMMdd");
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String format = null;

                    for (Map<String, Object> d : list) {
                        date = d.get("date").toString();
                        Date parse = sdfD.parse(date);
                        format = simpleDateFormat.format(parse);
                        holidays.add(format);
                    }

                }

            }

        }
        return holidays;
    }
}
